<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box,
        .box2 {
            width: 100px;
            height: 100px;
            background: red;
            position: absolute;
            top: 200px;
        }

        .box {
            left: 500px;
        }

        .box2 {
            right: 500px;
        }
    </style>
</head>

<body>
    <div class="box"></div>
    <div class="box2"></div>
</body>
<script type="text/javascript">
    var zIndex = 1
    window.onload = function () {
        const box = document.querySelector('.box')
        const box2 = document.querySelector('.box2')
         box.style.cursor = "move"
         box2.style.cursor = "move"
        drag(box)
        drag(box2)

    }
    function drag(oDrag) {
        var disX = dixY = 0;
        oDrag.onmousedown = function (event) {
            var event = event || window.event;
            disX = event.clientX - this.offsetLeft;
            disY = event.clientY - this.offsetTop;

            var oTemp = document.createElement("div");
            oTemp["id"] = "temp";
            oTemp.style.left = this.currentStyle ? this.currentStyle["left"] : getComputedStyle(this, null)["left"];
            oTemp.style.top = this.currentStyle ? this.currentStyle["top"] : getComputedStyle(this, null)["top"];
            oTemp.style.zIndex = zIndex++;
            document.body.appendChild(oTemp);

            document.onmousemove = function (event) {
                var event = event || window.event;
                var iL = event.clientX - disX;
                var iT = event.clientY - disY;
                var maxL = document.documentElement.clientWidth - oDrag.offsetWidth;
                var maxT = document.documentElement.clientHeight - oDrag.offsetHeight

                iL <= 0 && (iL = 0);
                iT <= 0 && (iT = 0);
                iL >= maxL && (iL = maxL);
                iT >= maxT && (iT = maxT);

                oTemp.style.left = iL + "px";
                oTemp.style.top = iT + "px";
                return false;
            };

            document.onmouseup = function () {
                document.onmousemove = null;
                document.onmouseup = null;
                oDrag.style.left = oTemp.style.left;
                oDrag.style.top = oTemp.style.top;
                oDrag.style.zIndex = oTemp.style.zIndex;
                document.body.removeChild(oTemp);
                oDrag.releaseCapture && oDrag.releaseCapture()
            };

            this.setCapture && this.setCapture();
            return false;
        }
    }


</script>

</html>